<?php

include '../vendor/autoload.php';

use EthTool\Callback;
use EthTool\Credential;

use Web3\Utils;

use Web3\Web3;
use Web3\Providers\HttpProvider;
use Web3\RequestManagers\HttpRequestManager;

date_default_timezone_set('PRC');

$time = time();//订单生成时间
$uid = 17;//用户ID
$order = 'EP'.date('YmdHis',$time).rand(0,1000000);//生成订单号
$income = 10;//订单金额 USDT
$ether = strval($income/4039);
$wei = Utils::toWei($ether,'ether')->toString();//换算成以太币需要的wei
$status = 0;//订单状态  0 订单生成 1支付成功 2订单完成 4订单取消 9订单失败

$wallet = Credential::new();//生成一个收款用的钱包

$address = $wallet->getAddress();//收款钱包地址
$privatekey = $wallet->getPrivateKey();//收款钱包私钥(不对外展示)

$balance = 0;//到账金额

$cb = new Callback();
// 轮询 计划任务 检查钱包余额
// 30分钟后 余额为0 关闭订单 $status=4;
// 余额>0 修改订单状态
$web3 = new Web3(new HttpProvider(new HttpRequestManager('http://127.0.0.1:8545', 5)));
$web3->eth->getBalance($address,'latest',$cb);
echo 'balance in latest block: ' . $cb->result . PHP_EOL;

if ($cb->result>=$wei) {
	$status=1;
	$rst = true;// $rst = pay2game();
	if ($rst) {
		$status=2;
	}else{
		$status=9;
	}
}

echo 'time:';
var_dump($time);
echo 'uid:';
var_dump($uid);
echo 'order:';
var_dump($order);
echo 'income:';
var_dump($income);
echo 'ether:';
var_dump($ether);
echo 'wei:';
var_dump($wei);
echo 'address:';
var_dump($address);
echo 'privatekey:';
var_dump($privatekey);
echo 'status:';
var_dump($status);


// ---转账
$credential = Credential::fromKey('546cf85447f87840d7095d5d05f4e14e2ed14f8a7246462be8275cbe9b449d41');

echo '转账' . PHP_EOL;
$web3->eth->getTransactionCount($credential->getAddress(),'latest',$cb); 
$nonce =  $cb->result;

$raw = [
    'nonce' => Utils::toHex($nonce,true),
    'gasPrice' => '0x' . Utils::toWei('20','gwei')->toHex(),
    'gasLimit' => '0x76c0',
    'to' => $address,
    'value' => '0x'.Utils::toWei($ether,'ether')->toHex(),
    'data' => '0x' . bin2hex('hello'),
    'chainId' => 10
];
$req = $credential->signTransaction($raw);

$web3->eth->sendRawTransaction($req,$cb);
echo 'tx hash: ' . $cb->result . PHP_EOL;
waitForReceipt($web3,$cb->result);

$web3->eth->getBalance($address,$cb);
echo 'wallet balance: ' . $cb->result . PHP_EOL;

function waitForReceipt($web3,$txhash,$timeout=60,$interval=1){
	$cb = new Callback;
	$t0 = time();
	while(true){
		$web3->eth->getTransactionReceipt($txhash,$cb);       
		if($cb->result) break;
		$t1 = time();
		if(($t1 - $t0) > $timeout) break;
		sleep($interval);  
	}
	return $cb->result;
}